package com.androidbegin.jsonparsetutorial;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidbegin.jsonparsetutorial.*;
import com.loopj.android.http.AsyncHttpClient;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class MainActivity extends Activity {
	// Declare Variables
	JSONObject jsonobject;
	JSONArray jsonarray;
	ListView listview;
	ListViewAdapter adapter;
	EditText inputSearch;
	ProgressDialog mProgressDialog;
	Button btndetete;
	ArrayList<HashMap<String, String>> arraylist;
	static String ID = "id";
	static String CONTENT = "content_detail";
	static String IMAGE = "image_thumbnail";
	static String Quantity;
	static String currentString;
	static String searchString;
	private static String url = "http://service3.topprinter.org/phototamtayvn-rest";
	HashMap<String, String> resultp = new HashMap<String, String>();
	CheckBox cbcheck;
	final AsyncHttpClient client = new AsyncHttpClient();
	HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from listview_main.xml
		//
		setContentView(R.layout.listview_main);

		if (!isNetworkAvailable(this)) {
			Toast.makeText(this, "No Internet connection", Toast.LENGTH_LONG)
					.show();
			finish();
		} else {
			Toast.makeText(this, "Internet connection", Toast.LENGTH_LONG)
					.show();
			// registerForContextMenu(listview);
			new DownloadJSON().execute();
		}

	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager conMan = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conMan.getActiveNetworkInfo() != null
				&& conMan.getActiveNetworkInfo().isConnected())
			return true;
		else
			return false;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
//		cbcheck = (CheckBox) findViewById(R.id.cbimg);
		
		// cbcheck.setChecked((state.get(position) == null ? false : true));
		// String selectedFromList = (listview.getItemAtPosition(position));s
		switch (item.getItemId()) {
		case R.id.deleteItem:
			showSelectedItemIds();
//			SparseBooleanArray checkedItemPositions = listview.getCheckedItemPositions();
//			int itemCount = listview.getCount();
//			for(int i=itemCount-1; i >= 0; i--){
//	            if(checkedItemPositions.get(i)){
//	                arraylist.remove(i);
//	            }
//	        }
//			 checkedItemPositions.clear();
//			 adapter.notifyDataSetChanged();
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);

		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		searchView.setIconifiedByDefault(true);

		SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextChange(String newText) {
				if (newText != null && newText.toString().length() > 0) {
					ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
					String filterString = newText.toString().toLowerCase();
					String filterableString;
					for (int i = 0; i < arraylist.size(); i++) {
						filterableString = arraylist.get(i).get(
								MainActivity.CONTENT);
						if (filterableString.trim().toLowerCase()
								.startsWith(filterString.trim().toLowerCase())) {
							arrayTemplist.add(arraylist.get(i));
						}
					}
					adapter = new ListViewAdapter(MainActivity.this,
							arrayTemplist);
					listview.setAdapter(adapter);
				} else {
					return false;
				}
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {
				// this is your adapter that will be filtered
				adapter.getFilter().filter(query);
				return true;
			}
		};
		searchView.setOnQueryTextListener(textChangeListener);

		return super.onCreateOptionsMenu(menu);
	}
	private void showSelectedItemIds() {
		final StringBuffer sb = new StringBuffer("Selection: ");
		// Get an array that contains the IDs of the list items that are checked
		// --
		final long[] checkedItemIds = listview.getCheckItemIds();
		if (checkedItemIds == null) {
			Toast.makeText(this, "No selection", Toast.LENGTH_LONG).show();
			return;
		}
		// For each ID in the status array
		boolean isFirstSelected = true;
		final int checkedItemsCount = checkedItemIds.length;
		for (int i = 0; i < checkedItemsCount; ++i) {
			if (!isFirstSelected) {
				sb.append(", ");
			}
			sb.append(checkedItemIds[i]);
			isFirstSelected = false;
		}
		// Show a message with the country IDs that are selected
		// --
		Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
	}
	// DownloadJSON AsyncTask
	private class DownloadJSON extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(MainActivity.this);
			// Set progressdialog message
			mProgressDialog.setMessage("Loading...");
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array
			arraylist = new ArrayList<HashMap<String, String>>();
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			try {
				// Locate the array name in JSON
				JSONObject jsonObj = new JSONObject(jsonStr);
				jsonarray = jsonObj.getJSONArray("data");

				for (int i = 0; i < jsonarray.length(); i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					jsonobject = jsonarray.getJSONObject(i);

					map.put("id", jsonobject.getString("id"));
					map.put("content_detail",
							jsonobject.getString("content_detail"));
					map.put("image_thumbnail",
							jsonobject.getString("image_thumbnail"));

					arraylist.add(map);
				}
				// Log.e("Array", "" + arraylist);
			} catch (JSONException e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			listview = (ListView) findViewById(R.id.listview);
			// Pass the results into ListViewAdapter.java
			adapter = new ListViewAdapter(MainActivity.this, arraylist);
			// Set the adapter to the ListView
			listview.setAdapter(adapter);
			// Close the progressdialog
			mProgressDialog.dismiss();
		}
	}
}